package shoppersservlets;

import infraestructura.PersistenceManager;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import modelo.User;

@WebServlet(name = "Login", urlPatterns = {"/login"})
public class Login extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession(false);
        if (noHaIniciadoLa(session)) {
            request.getRequestDispatcher("./WEB-INF/login.jsp").forward(request, response);
        } else {
            request.getRequestDispatcher("./WEB-INF/index.jsp").forward(request, response);
        }
    }

    private boolean noHaIniciadoLa(HttpSession session) {
        return session == null || session.getAttribute("user") == null;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");        
        PersistenceManager mang = PersistenceManager.getPersistenceManager(getServletContext().getInitParameter("persistenceMethod"));
        String username = request.getParameter("usuario");
        String password = request.getParameter("clave");
        if (mang.userExists(username, password)) {
            HttpSession session = request.getSession();
            User userData = mang.getUser(username, password);
            //@Abraham User, al igual que todo lo que se almacena en la sesin, debería ser 
            //serializable, o el día que despliegues esto en un cluster tendrás problemas
            session.setAttribute("user", userData);
            if (userData.isAdmin()) {
                response.sendRedirect("./admin/admin.jsp");
            } else {
                request.getRequestDispatcher("./index.jsp").forward(request, response);
            }
        } else {
            request.setAttribute("error", 1);
            request.getRequestDispatcher("./WEB-INF/login.jsp").forward(request, response);
        }
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
